<template>
  <view class="min-h-screen bg-[#f5f5f5]">
    <!-- 自定义导航栏 -->
    <navigationBar title="我的积分" />

    <!-- 积分统计卡片 -->
    <view class="card">
      <view
        class="bg-gradient-to-r from-[#AF6C31] to-[#D4A458] text-white p-[40rpx] rounded-t-[16rpx]"
      >
        <view class="text-center">
          <text class="text-[28rpx] opacity-90">当前积分</text>
          <view class="text-[60rpx] font-bold mt-[10rpx]">{{
            statistics.balance || 0
          }}</view>
        </view>

        <!-- <view
          class="flex justify-center mt-[40rpx]"
          v-if="statistics.description"
        >
          <view class="text-center">
            <view class="text-[24rpx] opacity-80">最近变动</view>
            <view class="text-[28rpx] font-medium mt-[8rpx]">{{
              statistics.description.split("：")[0]
            }}</view>
          </view>
          <view class="text-center flex-1">
            <view class="text-[24rpx] opacity-80">累计消费</view>
            <view class="text-[32rpx] font-medium mt-[8rpx]">{{
              statistics.totalSpentPoints || 0
            }}</view>
          </view>
          <view class="text-center flex-1">
            <view class="text-[24rpx] opacity-80">本月获得</view>
            <view class="text-[32rpx] font-medium mt-[8rpx]">{{
              statistics.monthlyEarnedPoints || 0
            }}</view>
          </view>
        </view> -->
      </view>
    </view>

    <!-- 积分记录标题 -->
    <view class="px-[30rpx] py-[20rpx]">
      <text class="text-[32rpx] text-[#121836] font-bold">积分明细</text>
    </view>

    <!-- 积分记录列表 -->
    <view class="px-[30rpx]">
      <view
        class="bg-white rounded-[16rpx] mb-[20rpx] p-[30rpx] shadow-sm"
        v-for="(record, index) in pointRecords"
        :key="record.id"
      >
        <view class="flex justify-between items-start">
          <view class="flex-1">
            <view class="flex items-center mb-[8rpx]">
              <view
                class="w-[8rpx] h-[8rpx] rounded-full mr-[12rpx]"
                :class="
                  record.pointChange > 0 ? 'bg-[#52C41A]' : 'bg-[#FF6B6B]'
                "
              ></view>
              <text class="text-[28rpx] text-[#121836] font-medium">{{
                record.description.split("：")[0]
              }}</text>
            </view>
            <text class="text-[24rpx] text-[#999] ml-[20rpx]">{{
              formatDate(record.createTime)
            }}</text>
          </view>
          <view class="text-right">
            <text
              class="text-[32rpx] font-bold"
              :class="
                record.pointChange > 0 ? 'text-[#52C41A]' : 'text-[#FF6B6B]'
              "
            >
              {{ record.pointChange > 0 ? "+" : "" }}{{ record.pointChange }}
            </text>
            <view class="text-[24rpx] text-[#999] mt-[4rpx]">
              余额: {{ record.balance }}
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <up-empty
        v-if="pointRecords.length === 0 && !loading"
        mode="list"
        text="暂无积分记录"
        marginTop="60"
      ></up-empty>
      <!-- 加载更多 -->
      <view
        class="text-center py-[40rpx]"
        v-if="hasMore && pointRecords.length > 0"
      >
        <up-loadmore
          :status="loadMoreStatus"
          bg-color="transparent"
          @loadmore="loadMore"
        />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { getMyPointRecords, getMyPointStatistics } from "@/api/my";
import type { PointRecordVO, PointStatisticsVO } from "@/api/my";
import navigationBar from "@/components/navigationBar/index.vue";

// 积分统计数据（最新的积分记录）
const statistics = reactive<PointStatisticsVO>({
  id: 0,
  userId: 0,
  orderId: 0,
  productId: 0,
  pointChange: 0,
  balance: 0,
  description: "",
  createTime: "",
  updateTime: "",
});

// 积分记录列表
const pointRecords = ref<PointRecordVO[]>([]);

// 分页参数
const pageNumber = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const loading = ref(false);
const loadMoreStatus = ref<"loading" | "loadmore" | "nomore">("loadmore");

onShow(() => {
  initData();
});

// 初始化数据
const initData = async () => {
  await Promise.all([loadPointStatistics(), loadPointRecords(true)]);
};

// 加载积分统计信息
const loadPointStatistics = async () => {
  try {
    const res = await getMyPointStatistics();
    if (res.code === 200 && res.data) {
      Object.assign(statistics, res.data);
    }
  } catch (error) {
    console.error("加载积分统计失败:", error);
    uni.showToast({
      title: "加载积分统计失败",
      icon: "none",
    });
  }
};

// 加载积分记录
const loadPointRecords = async (refresh = false) => {
  if (loading.value) return;

  loading.value = true;
  loadMoreStatus.value = "loading";

  try {
    if (refresh) {
      pageNumber.value = 1;
      hasMore.value = true;
    }

    const res = await getMyPointRecords(pageNumber.value, pageSize.value);

    if (res.code === 200 && res.data) {
      const newRecords = res.data.records || [];

      if (refresh) {
        pointRecords.value = newRecords;
      } else {
        pointRecords.value.push(...newRecords);
      }

      // 判断是否还有更多数据
      hasMore.value = pageNumber.value < res.data.totalPage;

      if (hasMore.value) {
        pageNumber.value++;
        loadMoreStatus.value = "loadmore";
      } else {
        loadMoreStatus.value = "nomore";
      }
    }
  } catch (error) {
    console.error("加载积分记录失败:", error);
    uni.showToast({
      title: "加载积分记录失败",
      icon: "none",
    });
    loadMoreStatus.value = "loadmore";
  } finally {
    loading.value = false;
  }
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    loadPointRecords();
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};
</script>

<style scoped>
.card {
  margin: 30rpx;
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
</style>
